package com.luohh.treeroom.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luohh.treeroom.dto.BaseResult;
import com.luohh.treeroom.dto.LoginParam;
import com.luohh.treeroom.dto.QQLoginParam;
import com.luohh.treeroom.entity.UserInfo;
import com.luohh.treeroom.mapper.UserInfoMapper;
import com.luohh.treeroom.redis.RedisParam;
import com.luohh.treeroom.service.IUserInfoService;
import com.luohh.treeroom.session.SessionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 罗辉煌
 * @since 2020-02-07
 */
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    @Autowired(required = false)
    UserInfoMapper userInfoMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    HttpServletRequest request;
    @Autowired
    EmailServiceImpl emailService;
    @Autowired
    SessionService sessionService;
    /**
     * yml配置默认头像
     */
    @Value("${default.image}")
    String defaultUserCover;

    /**
     * 根据号码查询用户
     * 如果查询失败注册账号
     *
     * @Synchronized自动加锁
     */
    @Synchronized
    private UserInfo getOrAddUser(LoginParam loginParam) throws Exception {

        // 根据手机号查询用户
        QueryWrapper<UserInfo> userQuery = new QueryWrapper<>();
        userQuery.eq("user_name", loginParam.getPhone());
        userQuery.eq("is_valid", 1);
        userQuery.eq("user_password",loginParam.getPassword());
        UserInfo userInfo = this.getOne(userQuery);

        // 没有该用户，注册
        if (userInfo == null) {

            //NEW一个UserInfo对象
            userInfo = new UserInfo();
            // 设置用户信息
            userInfo.setUserName(loginParam.getPhone());
            String nickName = "news" + loginParam.getPhone().substring(7, 11);
            userInfo.setNickName(nickName);
            String salt = "123";
            userInfo .setSalt(salt);
            userInfo.setPhone(loginParam.getPhone());
            userInfo.setUserPassword(loginParam.getPassword());
            userInfo.setImage(defaultUserCover);
            //获取现在时间
            Date now = new Date();
            //设置创建和更新时间
            userInfo.setCreateTime(now);
            userInfo.setUpdateTime(now);
//            String easemobUserName = StringUtil.getRandomString(16);
//            String easemobPassword = StringUtil.getRandomString(16);
//            userInfo.setEasemobUserName(easemobUserName);
//            userInfo.setEasemobPassword(easemobPassword);

            // 省市区
//            if (!StringUtil.isBlank(loginParam.getDistrictCode())) {
//                Region district = regionService.getByCode(loginParam.getDistrictCode());
//                Region city = regionService.getByCode(district.getPcode());
//                Region province = regionService.getByCode(city.getPcode());
//                userInfo.setDistrictId(district.getId());
//                userInfo.setDistrictName(district.getShortName());
//                userInfo.setCityId(city.getId());
//                userInfo.setCityName(city.getShortName());
//                userInfo.setProvinceId(province.getId());
//                userInfo.setProvinceName(province.getShortName());
//            } else {
//                userInfo.setCityName("珠海");
//                userInfo.setProvinceName("广东");
//            }
//
            userInfoMapper.insertReturnId(userInfo);
            log.debug(userInfo.toString());
//
            userInfo.setSex(1);// 性别：0女，1男
            userInfo.setIsValid(1);
//             计算年龄
//            Canlendar cal = Calendar.getInstance();
//            cal.setTime(new Date());
//            int nowYear = cal.get(Calendar.YEAR);
//            if (userInfo.getBirthday() != null) {
//                cal.setTime(userInfo.getBirthday());
//                int birthYear = cal.get(Calendar.YEAR);
//                int age = nowYear - birthYear;
//                userInfo.setAge(age);
//            } else {
//                userInfo.setAge(0);
//            }

        }


        // 过滤敏感数据
        userInfo.setUserName(null);
        userInfo.setUserPassword(null);
        return userInfo;
    }

    /**
     * 登录
     */
    @Override
    public BaseResult<UserInfo> phoneLogin(LoginParam loginParam) throws Exception {
        UserInfo userInfo = getOrAddUser(loginParam);
//        登陆方式
//        userInfo.setLoginType(1);// 1手机，2密码，3微信

        // 缓存token
        String token = request.getSession().getId();
        userInfo.setToken(token);
        redisTemplate.opsForValue().set(RedisParam.USER_INFO + token, JSON.toJSONString(userInfo), 2, TimeUnit.DAYS);
        redisTemplate.opsForValue().set(RedisParam.USER_ID + token, userInfo.getId() + "", 2, TimeUnit.DAYS);
        redisTemplate.opsForValue().set(RedisParam.USER_TOKEN + userInfo.getId(), token, 2, TimeUnit.DAYS);
        System.out.println(userInfo);
        log.debug("login token " + token + " userId " + userInfo.getId());
        // 过滤敏感数据
        userInfo.setUserName(null);
        userInfo.setUserPassword(null);

        return new BaseResult(userInfo);
    }

    @Override
    public BaseResult<UserInfo> getCode(String email)throws Exception{
        String verCode = (int) ((Math.random() * 9 + 1) * 1000) + "";
        log.debug("checkCode" + verCode);
        redisTemplate.opsForValue().set(RedisParam.EMAIL + email , verCode, 80, TimeUnit.MINUTES);
        BaseResult result = emailService.send(email,verCode);
        return new BaseResult();
    }

    @Override
    public BaseResult getDetail(){
        UserInfo user = this.getById(sessionService.getUserId());
        return new BaseResult(user);
    }

    @Override
    public BaseResult logout(){
        Integer userId = null;
        try {// 加catch是防止sessionService.getUserId()在失效时，会exception直接返回，导致后面代码不能执行
            userId = sessionService.getUserId();
        } catch (Exception e) {
            log.error("err", e);
        }

        // 清空token
        String token = request.getHeader("token");
        System.out.println(token);
        log.debug("logout token " + token + " userId " + userId);
        redisTemplate.delete(redisTemplate.keys(RedisParam.USER_INFO + token));
        redisTemplate.delete(redisTemplate.keys(RedisParam.USER_ID + token));
        redisTemplate.delete(redisTemplate.keys(RedisParam.USER_TOKEN + userId));

        return new BaseResult();
    }

    @Override
    public BaseResult<UserInfo> login(LoginParam loginParam) throws Exception {

        QueryWrapper userWrapper = new QueryWrapper();
        userWrapper.eq("user_name",loginParam.getPhone());
        UserInfo userInfo = this.getOne(userWrapper);
        if(userInfo == null){
            return new BaseResult("0","没有该用户",null);
        }else {
            userWrapper.eq("is_valid",1);
            userInfo = this.getOne(userWrapper);
            if (userInfo == null){
                return new BaseResult<>("0","账户失效",null);
            }else{
                userWrapper.eq("user_password",loginParam.getPassword());
                userInfo = this.getOne(userWrapper);
                if (userInfo == null){
                    return new BaseResult<>("0","密码错误",null);
                }
            }
        }
        userInfo.setUserPassword(null);
        return new BaseResult<>("1","成功",userInfo);
    }

    @Synchronized
    public UserInfo getOrAddQQ(QQLoginParam qqLoginParam) {
        String openID = qqLoginParam.getOpenid();
        QueryWrapper userWrapper = new QueryWrapper();
        userWrapper.eq("is_valid", 1);
        userWrapper.eq("openid", openID);
        UserInfo userInfo = this.getOne(userWrapper);
        if (userInfo == null) {
            //NEW一个UserInfo对象
            userInfo = new UserInfo();
            // 设置用户信息
            userInfo.setOpenid(qqLoginParam.getOpenid());
            String nickName = qqLoginParam.getNickName();
//        userInfo.setUserName("QQ登录");
            userInfo.setNickName(nickName);
//        userInfo.setPhone("123456");
            String salt = "123";
            userInfo.setSalt(salt);
            userInfo.setImage(defaultUserCover);
            //获取现在时间
            Date now = new Date();
            //设置创建和更新时间
            userInfo.setCreateTime(now);
            userInfo.setUpdateTime(now);
            Integer sex = qqLoginParam.getSex();
            userInfo.setSex(sex);// 性别：0女，1男
            userInfo.setIsValid(1);
            userInfoMapper.insert(userInfo);
        }
        return userInfo;
    }

    @Override
    public BaseResult qqLogin(QQLoginParam qqLoginPrames) throws Exception {
         UserInfo userInfo= getOrAddQQ(qqLoginPrames);
          String token = qqLoginPrames.getToken();
        redisTemplate.opsForValue().set(RedisParam.USER_INFO + token, JSON.toJSONString(userInfo), 2, TimeUnit.DAYS);
        redisTemplate.opsForValue().set(RedisParam.USER_ID + token, userInfo.getId() + "", 2, TimeUnit.DAYS);
        redisTemplate.opsForValue().set(RedisParam.USER_TOKEN + userInfo.getId(), token, 2, TimeUnit.DAYS);
        return new BaseResult(userInfo);
//        return null;
    }
}
